package com.itheima.bos.service.impl;

import com.itheima.bos.dao.IDecidedzoneDao;
import com.itheima.bos.dao.INoticebillDao;
import com.itheima.bos.dao.IWorkbillDao;
import com.itheima.bos.domain.Decidedzone;
import com.itheima.bos.domain.Noticebill;
import com.itheima.bos.domain.Staff;
import com.itheima.bos.domain.Workbill;
import com.itheima.bos.service.INoticebillService;
import com.itheima.crm.service.CustomerService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

/**
 * Created by Mr.King on 2017/3/15.
 */
@Service
@Transactional
public class NoticebillServiceImpl implements INoticebillService {

    @Autowired
    private INoticebillDao noticebillDao;
    @Autowired
    private IDecidedzoneDao decidedzoneDao;
    @Autowired
    private IWorkbillDao workbillDao;
    //注入代理对象
    @Autowired
    private CustomerService customerService;

    @Override
    public void save(Noticebill model) {
        noticebillDao.save(model);
        //尝试自动分单
        String pickaddress = model.getPickaddress();//客户的取件地址
        //通过代理对象调用crm服务，根据取件地址查询定区id
        String decidedzoneid = customerService.findDecidedzoneidByAddress(pickaddress);
        if(decidedzoneid != null){
            //可以自动分单
            Decidedzone decidedzone = decidedzoneDao.findById(decidedzoneid);
            //根据定区查询取派员
            Staff staff = decidedzone.getStaff();
            //业务通知单关联取派员
            model.setStaff(staff);
            //设置分单类型为“自动”
            model.setOrdertype("自动");
            //为当前取派员创建一个工单
            Workbill workbill = new Workbill();
            workbill.setAttachbilltimes(0);//追单次数
            workbill.setBuildtime(new Timestamp(System.currentTimeMillis()));//工单生成时间，系统时间
            workbill.setNoticebill(model);//工单关联业务通知单
            workbill.setPickstate("未取件");//取件状态：未取件、取件中、已取件
            workbill.setRemark(model.getRemark());//备注信息
            workbill.setStaff(staff);//工单关联取派员
            workbill.setType("新");//工单类型：新、追、改、销
            workbillDao.save(workbill);//保存工单
            //调用Webservice完成为当前取派员发送短信
        }else{
            //不能自动分单，转为人工分单
            model.setOrdertype("人工");
        }
    }
}
